/**
 * FileName: CategoryServiceImpl
 * Author:   sky
 * Date:     2019/12/27 11:43
 * Description:
 */
package com.run.guifeng.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.run.guifeng.dao.GoodsCategoryMapper;
import com.run.guifeng.model.entity.GoodsCategory;
import com.run.guifeng.model.enums.CategoryLevelEnum;
import com.run.guifeng.model.enums.ServiceResultEnum;
import com.run.guifeng.model.vo.IndexCategoryVO;
import com.run.guifeng.model.vo.SearchPageCategoryVO;
import com.run.guifeng.model.vo.SecondLevelCategoryVO;
import com.run.guifeng.service.CategoryService;
import com.run.guifeng.util.BeanUtil;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.groupingBy;

/**
 * @author sky
 * @create 2019/12/27
 * @since 1.0.0
 */
@Service
public class CategoryServiceImpl implements CategoryService {
    @Resource
    private GoodsCategoryMapper goodsCategoryMapper;

    @Override
    public List<GoodsCategory> getCategoriesPage(int categoryLevel, int parentId) {
        return goodsCategoryMapper.selectList(Wrappers.<GoodsCategory>lambdaQuery()
                .eq(GoodsCategory::getCategoryLevel, categoryLevel).eq(GoodsCategory::getParentId, parentId)
                .eq(GoodsCategory::getDeleted, false).orderByDesc(GoodsCategory::getCategoryRank));
    }

    /**
     * 以分类等级和名称
     *
     * @param goodsCategory
     * @return
     */
    @Override
    public String saveCategory(GoodsCategory goodsCategory) {
        GoodsCategory temp = goodsCategoryMapper.selectOne(Wrappers.<GoodsCategory>lambdaQuery()
                .eq(GoodsCategory::getCategoryLevel, goodsCategory.getCategoryLevel())
                .eq(GoodsCategory::getCategoryName, goodsCategory.getCategoryName()));
        if (temp != null) {
            return ServiceResultEnum.SAME_CATEGORY_EXIST.getResult();
        }
        if (goodsCategoryMapper.insert(goodsCategory) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public String updateGoodsCategory(GoodsCategory goodsCategory) {
        GoodsCategory temp = goodsCategoryMapper.selectById(goodsCategory.getId());
        if (temp == null) {
            return ServiceResultEnum.DATA_NOT_EXIST.getResult();
        }
        GoodsCategory temp2 = goodsCategoryMapper.selectOne(Wrappers.<GoodsCategory>lambdaQuery()
                .eq(GoodsCategory::getCategoryLevel, goodsCategory.getCategoryLevel())
                .eq(GoodsCategory::getCategoryName, goodsCategory.getCategoryName()));
        if (temp2 != null && !temp2.getId().equals(goodsCategory.getId())) {
            //同名且不同id 不能继续修改
            return ServiceResultEnum.SAME_CATEGORY_EXIST.getResult();
        }
        goodsCategory.setUpdateTime(new Date());
        if (goodsCategoryMapper.updateById(goodsCategory) > 0) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.DB_ERROR.getResult();
    }

    @Override
    public GoodsCategory getGoodsCategoryById(Integer id) {
        return goodsCategoryMapper.selectById(id);
    }

    @Override
    public String deleteBatch(Integer[] ids) {
        if (ids.length < 1) {
            return ServiceResultEnum.ERROR.getResult();
        }
        //删除分类数据
        if (goodsCategoryMapper.deleteBatchIds(Arrays.asList(ids)) == ids.length) {
            return ServiceResultEnum.SUCCESS.getResult();
        }
        return ServiceResultEnum.OPERATE_ERROR.getResult();
    }

    @Override
    public List<IndexCategoryVO> getCategoriesForIndex() {
        List<IndexCategoryVO> indexCategoryVOS = new ArrayList<>();
        //获取一级分类的固定数量的数据
        // 获取一级分类的所有数据
        List<GoodsCategory> firstLevelCategories = goodsCategoryMapper.selectList(Wrappers.<GoodsCategory>lambdaQuery()
                .in(GoodsCategory::getParentId, Collections.singletonList(0))
                .eq(GoodsCategory::getCategoryLevel, CategoryLevelEnum.LEVEL_ONE.getLevel())
                .eq(GoodsCategory::getDeleted, false).orderByDesc(GoodsCategory::getCategoryRank));

        if (!CollectionUtils.isEmpty(firstLevelCategories)) {
            List<Integer> firstLevelCategoryIds = firstLevelCategories.stream().map(GoodsCategory::getId).collect(Collectors.toList());
            //获取二级分类的数据
            List<GoodsCategory> secondLevelCategories = goodsCategoryMapper.selectList(Wrappers.<GoodsCategory>lambdaQuery()
                    .in(GoodsCategory::getParentId, firstLevelCategoryIds)
                    .eq(GoodsCategory::getCategoryLevel, CategoryLevelEnum.LEVEL_TWO.getLevel())
                    .eq(GoodsCategory::getDeleted, false).orderByDesc(GoodsCategory::getCategoryRank));
            //处理一级分类
            if (!CollectionUtils.isEmpty(secondLevelCategories)) {
                //根据 parentId 将 thirdLevelCategories 分组
                Map<Integer, List<GoodsCategory>> secondLevelCategoryVOMap =
                        secondLevelCategories.stream().collect(groupingBy(GoodsCategory::getParentId));
                for (GoodsCategory firstCategory : firstLevelCategories) {
                    IndexCategoryVO mallIndexCategoryVO = new IndexCategoryVO();
                    BeanUtil.copyProperties(firstCategory, mallIndexCategoryVO);
                    //如果该一级分类下有数据则放入 newBeeMallIndexCategoryVOS 对象中
                    if (secondLevelCategoryVOMap.containsKey(firstCategory.getId())) {
                        //根据一级分类的id取出secondLevelCategoryVOMap分组中的二级级分类list
                        List<GoodsCategory> tempGoodsCategories = secondLevelCategoryVOMap.get(firstCategory.getId());
                        mallIndexCategoryVO.setSecondLevelCategoryVOS((BeanUtil.copyList(tempGoodsCategories, SecondLevelCategoryVO.class)));
                        indexCategoryVOS.add(mallIndexCategoryVO);
                    }
                }
            }
            return indexCategoryVOS;
        } else {
            return null;
        }

    }

    @Override
    public SearchPageCategoryVO getCategoriesForSearch(Integer categoryId) {
        SearchPageCategoryVO searchPageCategoryVO = new SearchPageCategoryVO();
        GoodsCategory secondLevelGoodsCategory = goodsCategoryMapper.selectById(categoryId);
        if (secondLevelGoodsCategory != null && secondLevelGoodsCategory.getCategoryLevel() == CategoryLevelEnum.LEVEL_THREE.getLevel()) {
            //获取当前二级分类的一级分类
            GoodsCategory firstLevelGoodsCategory = goodsCategoryMapper.selectById(secondLevelGoodsCategory.getParentId());
            if (firstLevelGoodsCategory != null && firstLevelGoodsCategory.getCategoryLevel() == CategoryLevelEnum.LEVEL_TWO.getLevel()) {
                //获取当前一级分类下的二级分类List
                List<GoodsCategory> thirdLevelCategories = goodsCategoryMapper.selectList(Wrappers.<GoodsCategory>lambdaQuery()
                        .in(GoodsCategory::getParentId, Collections.singletonList(firstLevelGoodsCategory.getId()))
                        .eq(GoodsCategory::getCategoryLevel, CategoryLevelEnum.LEVEL_THREE));
                searchPageCategoryVO.setCurrentCategoryName(secondLevelGoodsCategory.getCategoryName());
                searchPageCategoryVO.setSecondLevelCategoryName(firstLevelGoodsCategory.getCategoryName());
                searchPageCategoryVO.setThirdLevelCategoryList(thirdLevelCategories);
                return searchPageCategoryVO;
            }
        }
        return null;
    }

    @Override
    public List<GoodsCategory> selectByLevelAndParentIdsAndNumber(List<Integer> parentIds, int categoryLevel) {
        return goodsCategoryMapper.selectList(Wrappers.<GoodsCategory>lambdaQuery().in(GoodsCategory::getParentId, parentIds)
                .eq(GoodsCategory::getCategoryLevel, categoryLevel));
    }


}